package com.redxiii.spike.util.core;

import com.redxiii.spike.api.communication.CommunicationService;
import com.redxiii.spike.api.communication.SecureChannelService;
import com.redxiii.spike.api.engine.Engine;

/**
 * @author Daniel Filgueiras
 * @since 19/06/2011
 */
public final class EngineSession {

	private static final ThreadLocal<CommunicationService> cService;
	private static final ThreadLocal<SecureChannelService> sChannel;
	private static final ThreadLocal<Engine> engineCore;
	private static final ThreadLocal<Boolean> keepAlive;
	
	static {
		cService = new InheritableThreadLocal<CommunicationService>();
		engineCore = new InheritableThreadLocal<Engine>();
		keepAlive = new InheritableThreadLocal<Boolean>();
		sChannel = new InheritableThreadLocal<SecureChannelService>();
	}
	
	public static CommunicationService getCommunicationService() {
		return cService.get();
	}
	
	public static void setCommunicationService(CommunicationService service) {
		if (cService.get() == null)
			cService.set(service);
		else
			throw new IllegalStateException("Can not set twice");
	}
	
	public static SecureChannelService getSecureChannelService() {
		return sChannel.get();
	}
	
	public static void setSecureChannelService(SecureChannelService channel) {
		if (sChannel.get() == null) 
			sChannel.set(channel);
		else
			throw new IllegalStateException("Can not set twice");
	}
	
	public static Engine getEngine() {
		return engineCore.get();
	}
	
	public static void setEngine(Engine engine) {
		keepAlive.set(Boolean.TRUE);
		
		if (engineCore.get() == null) {
			engineCore.set(engine);
		} else
			throw new IllegalStateException("Can not set twice");
	}
	
	public static boolean isAlive() {
		return keepAlive.get();
	}
	
	public static void sessionShutdown() {
		keepAlive.set(Boolean.FALSE);
	}
}
